package com.lanhai.utils;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetSocketAddress;
import com.lanhai.utils.HexUtil;
/**
 * UDP协议发送数据工具类
 * @author liangmin
 *
 */
public class UDPUtil {
    
	   public static void sendData(byte[] data, String ipAddress, int port, int sendPort){
		   ByteArrayOutputStream baos = new ByteArrayOutputStream();
		   DataOutputStream dos = new DataOutputStream(baos);
		   DatagramSocket ds = null;
		   try{
			   dos.write(data);
			   byte[] buf = baos.toByteArray();
			   DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress(ipAddress, port));
			   System.out.println("ip:" + ipAddress + ":" + port + ",data:" + HexUtil.byte2HexStr(data));
			   ds = new DatagramSocket(sendPort);
			   ds.send(dp);		   
		   }catch(Exception e){
			   e.printStackTrace();
		   }finally{
			   ds.close();
		   }
	   }

	   public static void sendData4Byte(byte[] data, String ipAddress, int port){
		   ByteArrayOutputStream baos = new ByteArrayOutputStream();
		   DataOutputStream dos = new DataOutputStream(baos);
		   DatagramSocket ds = null;
		   try{
			   dos.write(data);
			   byte[] buf = baos.toByteArray();
			   DatagramPacket dp = new DatagramPacket(buf, buf.length, new InetSocketAddress(ipAddress, port));
			   //System.out.println("ip:" + ipAddress + ",data:" + HexUtil.byte2HexStr(data));
			   ds = new DatagramSocket(9998);
			   ds.send(dp);		   
		   }catch(Exception e){
			   e.printStackTrace();
		   }finally{
			   ds.close();
		   }
	   }	   
	   
}
